package com.peng.leetcode.array;

import java.util.HashMap;
import java.util.Map;

/**
 * LengthOfLongestSubstring
 *
 * 剑指 Offer 48. 最长不含重复字符的子字符串
 *
 * @author: lupeng6
 * @create: 2021/3/25 14:47
 */
public class LengthOfLongestSubstring {

    public static void main(String[] args) {
        String s = "abcabcbb";
        System.out.println(new LengthOfLongestSubstring().lengthOfLongestSubstring(s));
    }

    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> charIndex = new HashMap<>();
        int length = s.length();
        int leftIndex = -1;
        int answer = 0;
        for (int i = 0; i < length; i++) {
            Character c = s.charAt(i);
            if (charIndex.containsKey(c)) {
                leftIndex = Math.max(leftIndex, charIndex.get(c));
            }
            charIndex.put(c, i);
            answer = Math.max(i - leftIndex, answer);
        }
        return answer;
    }
}
